package com.juyu.miliao.common.util;

import java.util.*;


/**
 *  集合分组
 * @Auther: 卜加超
 * @Date: 2019/2/22 09:25
 * @Description:
 */
public class ListGroupUtil {
    /***
     *  集合分组
     * @param list 分组集合
     * @param quantity 分组数量
     * @param <T>
     * @return
     */
    public static  <T> List<List<T>> groupListByQuantity(List<T> list, int quantity) {
        if (list == null || list.size() == 0) {
            return null;
        }

        if (quantity <= 0) {
            new IllegalArgumentException("Wrong quantity.");
        }

        List<List<T>> wrapList = new ArrayList<List<T>>();
        int count = 0;
        while (count < list.size()) {
            wrapList.add(new ArrayList<T>(list.subList(count, (count + quantity) > list.size() ? list.size() : count + quantity)));
            count += quantity;
        }

        return wrapList;
    }

    /**从list中随机抽取元素
     * @return
     * @Title: createRandomList
     * @Description: TODO
     * @param list
     */
    public static <T>List<T> createRandomList(List<T> list, int n) {
        Map map = new HashMap();
        List<T> listNew = new ArrayList();
        if (list.size() < n) {
            return list;
        } else {
            while (map.size() < n) {
                int random = (int) (Math.random() * list.size());
                if (!map.containsKey(random)) {
                    map.put(random, "");
                    listNew.add(list.get(random));
                }
            }
            return listNew;
        }
    }

    public static <T> T randomListToObject(List<T> list){
        Random random = new Random();
        int n = random.nextInt(list.size());
        return list.get(n);
    }
}
